package com.yami.shop.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yami.shop.common.config.SinaShortUrlConfig;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.service.SinaShortUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 新浪短链接服务实现类
 */
@Service
@Slf4j
public class SinaShortUrlServiceImpl implements SinaShortUrlService {

    @Resource
    private SinaShortUrlConfig sinaShortUrlConfig;
    
    @Resource
    private RestTemplate restTemplate;
    
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public ResponseEntity<String> generateShortUrl(String longUrl) {
        if (longUrl == null || longUrl.isEmpty()) {
            throw new YamiShopBindException("长链接不能为空");
        }
        
        try {
            // 构建请求参数
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("source", sinaShortUrlConfig.getAppKey());
            params.add("url_long", longUrl);
            
            // 构建请求URL
            String url = UriComponentsBuilder.fromHttpUrl(sinaShortUrlConfig.getApiUrl())
                    .queryParams(params)
                    .toUriString();
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    new HttpEntity<>(headers),
                    String.class
            );
            
            // 解析响应
            String responseBody = response.getBody();
            JsonNode jsonNode = objectMapper.readTree(responseBody);
            
            // 检查是否有错误
            if (jsonNode.has("error_code")) {
                String errorCode = jsonNode.get("error_code").asText();
                String errorMsg = jsonNode.get("error").asText();
                log.error("新浪短链接生成失败: code={}, msg={}", errorCode, errorMsg);
                throw new YamiShopBindException("新浪短链接生成失败: " + errorMsg);
            }
            
            // 获取短链接
            JsonNode urls = jsonNode.get("urls");
            if (urls != null && urls.isArray() && urls.size() > 0) {
                String shortUrl = urls.get(0).get("url_short").asText();
                return ResponseEntity.ok(shortUrl);
            } else {
                throw new YamiShopBindException("新浪短链接生成失败: 返回数据格式错误");
            }
        } catch (IOException e) {
            log.error("新浪短链接生成失败", e);
            throw new YamiShopBindException("新浪短链接生成失败: " + e.getMessage());
        }
    }

    @Override
    public ResponseEntity<String[]> batchGenerateShortUrl(String[] longUrls) {
        if (longUrls == null || longUrls.length == 0) {
            throw new YamiShopBindException("长链接不能为空");
        }
        
        if (longUrls.length > 20) {
            throw new YamiShopBindException("批量生成短链接最多支持20个链接");
        }
        
        try {
            // 构建请求参数
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("source", sinaShortUrlConfig.getAppKey());
            
            // 添加多个长链接
            for (String longUrl : longUrls) {
                params.add("url_long", longUrl);
            }
            
            // 构建请求URL
            String url = UriComponentsBuilder.fromHttpUrl(sinaShortUrlConfig.getApiUrl())
                    .queryParams(params)
                    .toUriString();
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    new HttpEntity<>(headers),
                    String.class
            );
            
            // 解析响应
            String responseBody = response.getBody();
            JsonNode jsonNode = objectMapper.readTree(responseBody);
            
            // 检查是否有错误
            if (jsonNode.has("error_code")) {
                String errorCode = jsonNode.get("error_code").asText();
                String errorMsg = jsonNode.get("error").asText();
                log.error("新浪短链接批量生成失败: code={}, msg={}", errorCode, errorMsg);
                throw new YamiShopBindException("新浪短链接批量生成失败: " + errorMsg);
            }
            
            // 获取短链接列表
            JsonNode urls = jsonNode.get("urls");
            if (urls != null && urls.isArray() && urls.size() > 0) {
                List<String> shortUrls = new ArrayList<>();
                for (JsonNode urlNode : urls) {
                    shortUrls.add(urlNode.get("url_short").asText());
                }
                return ResponseEntity.ok(shortUrls.toArray(new String[0]));
            } else {
                throw new YamiShopBindException("新浪短链接批量生成失败: 返回数据格式错误");
            }
        } catch (IOException e) {
            log.error("新浪短链接批量生成失败", e);
            throw new YamiShopBindException("新浪短链接批量生成失败: " + e.getMessage());
        }
    }
} 